<?php


namespace app\forum\controller;


use app\BaseController;
use app\libs\exception\ParamException;
use app\model\DiscussModel;

class Home extends BaseController
{
    /**
     * @throws \app\libs\exception\NotFoundException
     * @throws \app\libs\exception\ServerError
     */
    public function getDiscuss(): \think\response\Json
    {
        $page = $this->request->get('page', 0);
        $limit = $this->request->get('limit', 15);
        $query_condition = (new DiscussModel())
            ->field(['id', 'author_id', 'title', 'pv', 'create_time']);
        $discuss_list = $query_condition
            ->with('user')
            ->page($page, $limit)
            ->select();

        $result = [
            'current_page' => $page,
            'limit_row' => $limit,
            'count' => $query_condition->count(),
            'result' => $discuss_list
        ];
        return json($result);
    }

    /**
     * @throws \app\libs\exception\NotFoundException
     * @throws \app\libs\exception\ServerError
     */
    public function getDiscussDetail($id): \think\response\Json
    {
        $discuss = (new DiscussModel())->find_add_pv($id);

        return json($discuss);
    }

    /**
     * @throws ParamException
     */
    public function searchByTitle(): \think\response\Json
    {
        $title = $this->request->get('title');
        $page = $this->request->get('page', 0);
        $limit = $this->request->get('limit', 15);
        if (!$title) throw new ParamException(['msg' => '讨论的标题不能为空']);

        $query_condition = (new DiscussModel())->where('title', 'like', '%' . $title . '%');
        $discuss = $query_condition
            ->with(['user', 'user.img'])
            ->field(['id', 'title', 'author_id', 'create_time'])
            ->page($page, $limit)
            ->select();

        $result = [
            'current_page' => $page,
            'limit_row' => $limit,
            'count' => $query_condition->count(),
            'key_word' => $title,
            'result' => $discuss
        ];
        return json($result);
    }
}